package com.gnerv.sylvanas.authentication.server.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.Principal;
import java.util.Set;

@Controller
@RequestMapping(value = "")
public class AuthController {

    @Resource
    private RegisteredClientRepository registeredClientRepository;

    @GetMapping(value = "/api/oauth2/login")
    public String login() {
        return "login";
    }

    @GetMapping(value = "/api/oauth2/authorize")
    public String authorize(HttpServletRequest request, Principal principal,
                            @RequestParam(value = OAuth2ParameterNames.CLIENT_ID) String clientId,
                            @RequestParam(value = OAuth2ParameterNames.SCOPE) String scope,
                            @RequestParam(value = OAuth2ParameterNames.STATE) String state) {
        String name = principal.getName();
        RegisteredClient client = registeredClientRepository.findByClientId(clientId);
        String clientName = client.getClientName();
        String redirectUri = client.getRedirectUris().iterator().next();
        Set<String> scopes = client.getScopes();

        request.setAttribute("principalName", name);
        request.setAttribute("clientName", clientName);
        request.setAttribute("client_id", clientId);
        request.setAttribute("scopes", scopes);
        request.setAttribute("state", state);
        return "authorize";
    }

    @ResponseBody
    @RequestMapping(value = "/oauth2/token")
    public String token() {
        return "Hello World!";
    }

}
